#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <strings.h>

int main(int argc,char *argv[]){

    // 参数
    if (argc != 3){
        fprintf(stderr,"Usage argc ... \n");
        exit(-1);
    }

    // 得到通信文件描述符
    int cfd = socket(PF_INET,SOCK_DGRAM,0);
    if (cfd < 0){
        fprintf(stderr,"socket error!\n");
        exit(-1);
    } 

    // 设置服务器的ip地址和端口号
    struct sockaddr_in ser_addr;
    bzero(&ser_addr,sizeof(ser_addr));
    ser_addr.sin_family = AF_INET;
    ser_addr.sin_addr.s_addr = inet_addr(argv[1]);
    ser_addr.sin_port = htons(atoi(argv[2]));
    
    // 进行通信
    int str_len;
    char buf[1024];
    socklen_t ser_len = sizeof(ser_addr);
    while (1){
        fputs("[client] messgae(q to quit): ",stdout);
        memset(buf,'\0',sizeof(buf));
        fgets(buf,sizeof(buf),stdin);
        if(!strcmp(buf,"q\n") || !strcmp(buf,"Q\n")){
            break;
        }  
        sendto(cfd,buf,strlen(buf),0,(struct sockaddr *)&ser_addr,ser_len);
        str_len = recvfrom(cfd,buf,sizeof(buf),0,(struct sockaddr *)&ser_addr,&ser_len);
        buf[str_len] = '\0';
        printf("Message from server: %s\n",buf);
    }

    // 关闭
    close(cfd);
    return 0;
}